<template>
  <div class="profile-container">
    <!-- 返回按钮 -->
    <div class="back-button">
      <el-button icon="el-icon-back" @click="goBack">返回主页</el-button>
    </div>
    
    <h3>个人资料</h3>
    
    <el-form :model="form" :rules="rules" ref="form" label-width="100px" style="max-width: 600px" v-loading="loading">
      <!-- 头像上传区域 -->
      <el-form-item label="头像">
        <div class="avatar-container">
          <div class="avatar-wrapper">
            <img 
              v-if="form.avatar && form.avatar.startsWith('http')" 
              :src="form.avatar" 
              class="avatar-image" 
              @error="handleImageError"
              alt="头像" 
            />
            <img 
              v-else-if="form.avatar" 
              :src="`https://stu-work.oss-cn-shenzhen.aliyuncs.com/${form.avatar}`" 
              class="avatar-image" 
              @error="handleImageError"
              alt="头像" 
            />
            <img 
              v-else 
              :src="defaultAvatar" 
              class="avatar-image" 
              alt="默认头像" 
            />
          </div>
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :http-request="uploadAvatar"
            :before-upload="beforeAvatarUpload">
            <el-button size="small" type="primary">更换头像</el-button>
          </el-upload>
        </div>
      </el-form-item>
      
      <el-form-item label="工号" prop="teacherId">
        <el-input v-model="form.teacherId" disabled></el-input>
      </el-form-item>
      
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      
      <el-form-item label="所属院系" prop="department">
        <el-input v-model="form.departmentName" disabled></el-input>
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      
      <!-- 添加密码修改字段 -->
      <el-form-item label="新密码" prop="newPassword">
        <el-input type="password" v-model="form.newPassword" placeholder="不修改请留空" show-password></el-input>
        <span class="form-tip">如需修改密码，请直接输入新密码，留空则不修改</span>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">保存修改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getTeacherInfo, updateTeacherInfo, uploadTeacherAvatar } from '@/api/teacher'
import { getAllDepartments, updateTeacherPassword } from '@/api/admin'
import { mapGetters } from 'vuex'

export default {
  name: 'TeacherProfile',
  data() {
    // 手机号验证
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    
    // 邮箱验证
    const validateEmail = (rule, value, callback) => {
      if (value && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(value)) {
        callback(new Error('请输入正确的邮箱地址'))
      } else {
        callback()
      }
    }
    
    return {
      loading: false,
      submitting: false,
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      originalInfo: null, // 保存原始信息，用于重置
      isAdminEdit: false, // 是否是管理员编辑模式
      departments: [], // 院系列表
      form: {
        teacherId: '',
        name: '',
        department: '',
        departmentName: '', // 院系名称
        email: '',
        phone: '',
        avatar: '',
        newPassword: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    
    teacherId() {
      return this.userInfo.teacherId || localStorage.getItem('teacherId') || ''
    }
  },
  created() {
    this.fetchTeacherInfo()
    this.fetchDepartments()
  },
  methods: {
    // 获取教师信息
    fetchTeacherInfo() {
      if (!this.teacherId) {
        this.$message.error('未找到教师ID，请重新登录')
        return
      }
      
      this.loading = true
      getTeacherInfo(this.teacherId)
        .then(response => {
          if (response.code === 200 && response.data) {
            const teacherInfo = response.data
            console.log('获取到的教师信息:', teacherInfo)
            
            // 更新表单
            this.form = {
              teacherId: teacherInfo.teacherId || this.teacherId,
              name: teacherInfo.name || '',
              department: teacherInfo.deptNumber || teacherInfo.department || '',
              departmentName: teacherInfo.deptName || this.getDepartmentName(teacherInfo.deptNumber || teacherInfo.department) || '',
              email: teacherInfo.email || '',
              phone: teacherInfo.phone || '',
              avatar: teacherInfo.avatar || '',
              newPassword: ''
            }
            
            // 保存原始信息，用于重置
            this.originalInfo = JSON.parse(JSON.stringify(this.form))
          } else {
            this.$message.error(response.message || '获取教师信息失败')
          }
        })
        .catch(error => {
          console.error('获取教师信息失败:', error)
          this.$message.error('获取教师信息失败，请稍后重试')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 获取所有院系
    fetchDepartments() {
      getAllDepartments()
        .then(response => {
          if (response.code === 200) {
            this.departments = response.data || []
            
            // 如果已加载教师信息但departmentName为空，尝试再次获取
            if (this.form.department && !this.form.departmentName && this.departments.length > 0) {
              this.form.departmentName = this.getDepartmentName(this.form.department)
            }
          }
        })
        .catch(error => {
          console.error('获取院系列表失败:', error)
        })
    },
    
    // 根据院系ID获取院系名称
    getDepartmentName(deptNumber) {
      if (!deptNumber) return ''
      
      const dept = this.departments.find(d => d.deptNumber === deptNumber)
      return dept ? dept.deptName : ''
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitting = true
          
          // 准备更新的数据
          const updateData = {
            name: this.form.name,
            email: this.form.email,
            phone: this.form.phone,
            avatar: this.form.avatar,
            department: this.form.department
          }
          
          // 判断是否需要修改密码
          const needChangePassword = !!this.form.newPassword;
          
          // 创建一个Promise数组用于并行处理基本信息更新和密码修改
          const promises = [];
          
          // 添加基本信息更新的Promise
          promises.push(
          updateTeacherInfo(this.teacherId, updateData)
            .then(response => {
              if (response.code === 200) {
                // 更新本地存储和Vuex中的用户信息
                const updatedUserInfo = {
                  ...this.userInfo,
                  ...updateData
                }
                this.$store.dispatch('setUserInfo', updatedUserInfo)
                
                // 更新原始信息
                  this.originalInfo = JSON.parse(JSON.stringify({
                    ...this.form,
                    newPassword: ''
                  }))
                  
                  return Promise.resolve(true);
                } else {
                  return Promise.reject(new Error(response.message || '更新个人信息失败'));
                }
              })
          );
          
          // 如果需要修改密码，添加密码修改的Promise
          if (needChangePassword) {
            promises.push(
              updateTeacherPassword(
                this.teacherId, 
                this.form.newPassword
              ).then(response => {
                if (response.code === 200) {
                  // 清空密码字段
                  this.form.newPassword = '';
                  return Promise.resolve(true);
              } else {
                  return Promise.reject(new Error(response.message || '密码修改失败'));
                }
              })
            );
          }
          
          // 执行所有Promise
          Promise.all(promises)
            .then(() => {
              this.$message.success('个人信息更新成功');
              
              // 如果修改了密码，提示用户需要重新登录
              if (needChangePassword) {
                this.$confirm('密码已修改，需要重新登录才能生效。是否立即退出登录?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  // 退出登录并跳转到登录页
                  this.$store.dispatch('logout')
                  this.$router.push('/login')
                }).catch(() => {
                  // 用户取消，不做任何处理
                })
              }
            })
            .catch(error => {
              console.error('更新失败:', error)
              this.$message.error(error.message || '更新失败，请稍后重试')
            })
            .finally(() => {
              this.submitting = false
            })
        }
      })
    },
    
    // 重置表单
    resetForm() {
      if (this.originalInfo) {
        this.form = JSON.parse(JSON.stringify(this.originalInfo))
      } else {
        this.$refs.form.resetFields()
      }
    },
    
    // 返回主页
    goBack() {
      this.$router.push('/teacher/classes')
    },
    
    // 上传头像
    uploadAvatar(options) {
      const file = options.file
      this.$message.info('正在上传头像...')
      
      uploadTeacherAvatar(file)
        .then(response => {
          if (response.code === 200 && response.data) {
            console.log('头像上传成功，返回URL:', response.data)
            // 保存完整的URL，而不是相对路径
            let avatarUrl = response.data
            
            // 如果返回的URL不是以http开头，但是以/开头，可能是相对路径
            if (!avatarUrl.startsWith('http') && avatarUrl.startsWith('/')) {
              avatarUrl = avatarUrl.substring(1)
            }
            
            this.form.avatar = avatarUrl
            console.log('设置到表单的头像URL:', avatarUrl)
            
            // 立即更新到数据库，使用完整URL
            this.saveAvatarToDatabase(avatarUrl)
          } else {
            this.$message.error(response.message || '头像上传失败')
          }
        })
        .catch(error => {
          console.error('头像上传失败:', error)
          this.$message.error('头像上传失败，请稍后重试')
        })
    },
    
    // 添加保存头像到数据库的方法
    saveAvatarToDatabase(avatarUrl) {
      // 确保我们有URL可用
      if (!avatarUrl) {
        this.$message.error('头像URL为空，无法保存')
        return
      }
      
      console.log('准备保存到数据库的头像URL:', avatarUrl)
      
      const updateData = {
        avatar: avatarUrl
      }
      
      this.submitting = true
      this.$message.info('正在保存头像信息...')
      
      updateTeacherInfo(this.teacherId, updateData)
        .then(response => {
          if (response.code === 200) {
            this.$message.success('头像更新成功')
            console.log('头像保存成功，服务器返回:', response)
            
            // 更新本地存储和Vuex中的用户信息
            const updatedUserInfo = {
              ...this.userInfo,
              avatar: avatarUrl
            }
            this.$store.dispatch('setUserInfo', updatedUserInfo)
            
            // 更新原始信息
            if (this.originalInfo) {
              this.originalInfo.avatar = avatarUrl
            }
          } else {
            this.$message.error(response.message || '头像信息保存失败')
            console.error('头像保存失败，服务器返回:', response)
          }
        })
        .catch(error => {
          console.error('头像信息保存失败:', error)
          this.$message.error('头像信息保存失败，请稍后重试')
        })
        .finally(() => {
          this.submitting = false
        })
    },
    
    // 上传前验证
    beforeAvatarUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    
    // 头像错误处理
    handleImageError() {
      console.error('头像加载失败:', this.form.avatar)
      // 尝试使用完整URL或重试其他格式
      if (this.form.avatar && !this.form.avatar.startsWith('http')) {
        // 如果是相对路径，尝试拼接完整URL
        try {
          // 记录之前的头像URL以便于调试
          const prevUrl = this.form.avatar
          // 拼接完整URL
          this.form.avatar = `https://stu-work.oss-cn-shenzhen.aliyuncs.com/${this.form.avatar}`
          console.log(`尝试转换头像URL: ${prevUrl} => ${this.form.avatar}`)
          return // 不立即显示默认头像，让Vue重新尝试加载
        } catch (error) {
          console.error('处理头像URL失败:', error)
        }
      }
      
      // 使用默认头像代替
      this.$message.error('头像加载失败，使用默认头像')
      this.form.avatar = ''
    }
  }
}
</script>

<style scoped>
.profile-container {
  background-color: #fff;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-width: 700px;
  margin: 20px auto;
  position: relative;
}

h3 {
  margin-bottom: 30px;
  color: #303133;
  font-size: 22px;
  text-align: center;
}

/* 返回按钮样式 */
.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.avatar-uploader {
  margin-top: 5px;
}

.avatar-wrapper {
  position: relative;
  width: 100px;
  height: 100px;
  overflow: hidden;
  border-radius: 50%;
  margin-bottom: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 5px;
  display: block;
}
</style> 